<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <FortenScan
        propPlaceholder="请扫描送货单"
        propErrorMsg="请扫描正确的送货单"
        :propTypeFun="(scan)=> {return scan.toLowerCase().startsWith('po') || scan.toLowerCase().startsWith('cpo') || scan.toLowerCase().startsWith('an')  || scan.toLowerCase().startsWith('asn')}"
        @scanCall="handleScanOver"
        ref="scanDom"
      />

      <van-field label="送货单号:" label-align="right" v-model="deliver.code" size="mini" disabled />
      <van-field label="入库金额:" label-align="right" v-model="deliver.deliveryAmount" size="mini" disabled />
      <van-field label="供应商:" label-align="right" v-model="deliver.supplierName"  size="mini" disabled />
      <van-field label="订单号:" label-align="right" v-model="deliver.poCode" size="mini" disabled/>
      <van-field label="采购分类:" label-align="right" :value="formatBaseType(deliver.purchaseType)" size="mini" disabled/>
      <van-field label="发货温度:" label-align="right" type="number" v-model="deliver.temperature" size="mini" disabled v-show="deliver.purchaseType == 'reagent'"/>
      <van-field label="到货温度:" label-align="right" type="number" v-model="deliver.arrivalTemperature" size="mini" v-show="deliver.purchaseType == 'reagent'"/>
      <van-field label="配送试剂组：" label-align="left" v-model="deliver.reagentTeamName" size="mini" readonly is-link @click="showReagentPopup" v-show="deliver.purchaseType == 'reagent'"/>

    </van-cell-group>
    <van-collapse v-model="pictureActiveNames" v-show="deliver.purchaseType == 'reagent'">
      <van-collapse-item title="温度记录单" name="1">
        <van-uploader v-model="fileList" multiple
          capture="camera"
          :max-size="1000 * 1024"
          :max-count="5"
          :after-read="afterRead"
          :before-delete="fileDelete"
          @oversize="onOversize"/>
      </van-collapse-item>
    </van-collapse>

    <van-divider><span style="font-size:9px">入库单明细</span></van-divider>
    <div class="items-container">
      <deliver-item
        style="margin-top:5px;"
        v-for="item in deliverItems"
        :key="item.id"
        :value="item"
        @click.native="showPopup(item)"
      />
    </div>
    <van-row :gutter="10" type="flex" justify="space-around" class="footer-btn">
      <van-col :span="`${purchaseOrderType == 'reagent'? 7 : 14}`">
        <flow-buttons
          :propFlowKey="propFlowKey"
          :propDisabled="cpButtonDisable"
          @button-click="handleFlowButtonClick"
          />
      </van-col>
      <van-col span="7">
        <van-button text="打印标签" type="info" @click="utilPrint.print('inOrder', busId)" :disabled="!busId"></van-button>
      </van-col>
      <van-col span="7" v-if="purchaseOrderType == 'reagent'">
        <van-button text="一键配送试剂" type="danger" @click="handleAutoResponse" :disabled="flowStatus != 'end'"></van-button>
      </van-col>
    </van-row>

    <van-popup v-model="show" position="right" class="popup">
      <van-search v-model="deliver.reagentTeamName" placeholder="请输入关键词" shape="round"  background="#1989fa" @input="whfilter" />
      <van-checkbox-group>
        <van-cell-group>
          <van-cell
            v-for="(item, index) in searchedList"
            clickable
            :key="item.id"
            :title="item.name"
            @click="deptCheck(item, index)"
          >
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </van-popup>

    <van-popup v-model="ishow" closeable close-icon="close" position="bottom" :style="{ height: '90%' }">
      <van-swipe :autoplay="5000"  class ="my-swipe">
        <van-swipe-item v-for="(image, index) in images" :key="index"  @click.native="imgPreview(image)">
          <van-image class="imgs"  :src="image"   fit="fill" height="200" width="80%"/>
        </van-swipe-item>
      </van-swipe>
      <van-list
        v-model="loading"
        :finished="finished"
        :style="{}"
      >
        <van-cell  :title="'品名： '" :value="name"/>
        <van-cell  :title="'品规： '" :value="spec"/>
        <van-cell  :title="'批次： '" :value="lot"/>
        <van-cell  :title="'效期： '" :value="exp"/>
        <van-cell  :title="'包装数量： '" :value="packageQty"/>
        <van-cell  :title="'包装单位： '" :value="packageUnit"/>
        <van-cell  :title="'价格： ' " :value="price" />
        <van-cell  :title="'总价： ' " :value="amount"/>
      </van-list>
<!--      <div class="pop-container" :style="{marginTop: '10%', marginLeft: '10%', width: '80%', backgroundColor: ''}">-->
<!--        &lt;!&ndash;          :src="matr.thumbnailImageUrl"&ndash;&gt;-->
<!--        <div class="matr-img"  :style="{height: '100px', backgroundColor: 'gray'}">-->
<!--          <van-image ></van-image>-->
<!--        </div>-->
<!--        <div :style="{margin: '10px', backgroundColor: 'yellow', height: '30px'}">-->
<!--          <van-row lable="123" value="123">-->
<!--          </van-row>-->
<!--        </div>-->
<!--        <van-button type="primary" @click="saveOrUpdate" round :style="{width: '100%'}">保存</van-button>-->
<!--      </div>-->
    </van-popup>
  </div>
</template>

<script>
/* eslint-disable*/
import { Popup, List, Image as VanImage, NumberKeyboard, DatetimePicker, Swipe, SwipeItem, ImagePreview   } from 'vant'
import Vue from 'vue'
import FlowButtons from '@/components/FlowButtons.vue'
import DeliverItem from './DeliverItem.vue'
import commonMixin from '@/util/mixin/commonMixin'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(DatetimePicker)
Vue.use(VanImage)
Vue.use(NumberKeyboard)
Vue.use(List)
Vue.use(Popup)

export default {
  data() {
    return {
      scan: '',
      images: [],
      loading: false,
      asnKey: '',
      deliver: {},
      deliverItems: [],
      deliverItemMatrs: [],
      ishow: false,
      finished: true,
      name: '',
      spec: '',
      unit: '',
      packageUnit: '',
      qty: '0',
      packageQty: '0',
      price: '0.00',
      amount: '0.00',
      lot: '1',
      exp: '2020-09-10',
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      logoCenter: require('@/assets/img/matr/timg.jpg'),
      image: '',
      searchedList: [],
      show: false,
      pictureActiveNames: ['1'], //图片
      fileList: [],
      fileRefTable: 'purchase_order',
      baseApi: location.origin + '/api',
      busId: '',
      purchaseOrderType: '',
      flowStatus: ''
    }
  },
  mixins: [commonMixin],
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom.focus()
  },
  computed: {
    cpButtonDisable() {
      return !this.deliver.code
    },
  },
  methods: {
    handleScanClear(event) {
      this.scan = ''
    },
    handleScanOver(scanValue) {
      const params = {
        asnKey: scanValue,
        isScan: 1
      }
      this.utils.loadShow()
      this.clearForm()
      this.$ajax.get('/wm/in_order/getDelivery', { params }).then(response => {
        if (response.code == 0) {
          const deliver = response.data.deliver
          this.deliver = JSON.parse(JSON.stringify(deliver))
          this.asnKey = deliver && deliver.code
          this.purchaseOrderType = deliver.purchaseType
          this.deliverItems = deliver && deliver.items
          if (deliver.reagentTeamId) {
            this.getReagentTeam(deliver.reagentTeamId)
          }
          this.addMatrImageProp(response.data.matrs || [])
          this.getfiles()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
      this.$ajax.get('/wm/in_order/isExist', {params}).then(resp => {
        this.utils.loadHide()
      })
    },
    async handleFlowButtonClick(button) {
      if (this.deliver.purchaseType == 'reagent' && !this.deliver.reagentTeamId) {
        this.$notify.warning('请选择配送试剂组')
        return
      }

      const result = await this.$dialog.confirm({
        title: '流程确认',
        message: `确定要进行${button.title}操作吗？`
      })
      if (!result) return
      let params = {
        asnKey: this.asnKey,
        warehouseId: this.$store.getters.currentWarehouse.id,
        busUser: this.utils.getCurrentUser().name,
        arrivalTemperature: this.deliver.arrivalTemperature,
        reagentTeamId: this.deliver.reagentTeamId
      }
      this.utils.loadShow()
      const response = await this.$ajax.post('/wm/in_order/createByAsn', params)
      if (response.success) {
        this.busId = response.data
      } else {
        this.utils.loadHide()
        return
      }

      const flowKey = this.propFlowKey.split(':')[0]
      params = {
        flowKey,
        buttonKey: button.code,
        busId: this.busId,
        flowStatusTextFrom: '提交',
        flowStatusTextTo: '审核通过',
        busTable: 'std_audit_in',
        busIdName: this.busId,
        busTypeName: 'app/in-order'
      }
      this.$ajax.post('/wm/in_order/flow_change', params).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.$notify.success(`${button.title}操作成功！`)
          this.$set(this.deliver, 'flowStatus', 'end')
          this.flowStatus = 'end'
          this.clearForm()
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    addMatrImageProp(matrs) {
      this.deliverItems.forEach(deliverItem => {
        const matrMatch = matrs.find(matr => matr.mscmCode == deliverItem.materialCode)
        if (matrMatch) {
          deliverItem.thumbnailImageUrl = matrMatch.thumbnailImageUrl
        }
      })
    },
    clearForm() {
      this.asnKey = ''
      this.deliver = {}
      this.deliverItems = []
      this.scan = ''
      this.$refs.scanDom.focus()
    },
    showPopup(item) {
      const params = {
        mscmCode: item.materialCode
      }
      this.ishow = true
      this.name =  item.materialName
      this.spec =   item.materialSpec
      this.unit =   item.unit
      this.qty = item.qty
      this.packageQty =   (item.qty / item.orderQty) + item.orderUnit
      if (item.orderQty != 1.0) {
        this.packageUnit = item.orderQty + item.unit + '/' + item.orderUnit
      }
      this.lot =  item.lot
      this.exp =   item.expiredDate
      this.price =  (item.price * item.orderQty) + '/' + item.orderUnit
      this.amount =  item.subtotalAmount

      let that = this
      this.$ajax.post('/base/matr/getMatrByMscmCode', params).then(resp => {
        if (resp.code == 0) {
          that.loadFiles(resp.data)
        }
      })
    },

    //加载文件
    loadFiles(matrId) {
      this.$ajax.get(`tool/getFilesByRef?fileRefTable=base_matr&fileRefId=`+matrId, {}).then((response) => {
        if (response.code == 0) {
          if(response.data.length == 0) {
            this.images.push(this.logoCenter)
          }else  {
            let imagesArr = []
            response.data.forEach( ob => {
              this.images.push(ob.filePath)
            })
          }
        }
      }).finally(() => {
      }).catch(() => {
      })
    },

    imgPreview() {
      ImagePreview(this.images)
    },
    whfilter() {
      this.searchedList = this.searchedList.filter(item => item.name.indexOf(this.deliver.reagentTeamName) > -1
        || this.pyutils.chineseToPinYin(item.name).indexOf(this.deliver.reagentTeamName) > -1)
    },
    deptCheck(item, index){
      if (this.deliver.reagentTeamId == item.id) {
        this.show = false
        return
      }
      this.$set(this.deliver, 'reagentTeamId' , item.id)
      this.$set(this.deliver, 'reagentTeamName' , item.name)
      this.show = false
    },
    showReagentPopup() {
      this.show = true;
      this.utils.loadShow()
      this.getReagentTeam()
    },
    getReagentTeam(reagentTeamId){
      this.$ajax.get('/base/reagent_team/list').then(res => {
        this.utils.loadHide()
        if(res.code == 0){
          this.searchedList = res.data || []
          if (reagentTeamId) {
            const find = this.searchedList.find(s => s.id == reagentTeamId)
            this.deliver.reagentTeamName = find ? find.name: ''
          }
        }
      }).catch(err=> {
        this.utils.loadHide()
      })
    },
    async handleAutoResponse() {
      if (!this.busId) return
      const result = await this.$dialog.confirm({
        title: '操作确认',
        message: '确定要自动转成配送/调拨单?'
      })
      if (!result) return
      const params = {
        id: this.busId,
        purchaseOrderType: this.purchaseOrderType
      }
      this.$ajax.post('/wm/in_order/autoResponse', params).then(resp => {
        if (resp.code == 0) {
          this.purchaseOrderType = ''
          const {transferId, distId } = resp.data
          this.$dialog.confirm({
            title: '操作确认',
            message: `转换成功，是否打开${transferId ? '调拨' : '配送'}单？`
          }).then(() => {
            // eslint-disable-next-line no-nested-ternary
            transferId ? global.utils.openMenu('transfer-pick/index', {pid: transferId, toDetail: true}) : distId ? global.utils.openMenu('dist/dist-pick', {pid: distId, toDetail: true}) : false
          }).catch(()=>{})
        }
      })
    },
    afterRead(file) { //上传图片
      if(!this.deliver.id) return
      let params = new FormData()
      params.append('file', file.file)
      params.append('fileSavePath', this.fileRefTable)
      params.append('fileRefTable', this.fileRefTable)
      params.append('fileRefId', this.deliver.code)
      this.$ajax.post('/tool/uploadMore', params, {headers: {'Content-Type': 'multipart/form-data'}}).then(resp => {
        if (resp.code == 0) {
          this.getfiles()
        }
      })
    },
    getfiles() { //获取上传的图片
      let params = {
        fileRefTable: this.fileRefTable,
        fileRefId: this.deliver.code
      }
      this.$ajax.get('/tool/getFilesByRef', {params}).then((response) => {
        if (response.data && response.data.length) {
          this.fileList = response.data.map(file => {
            return {
              url: this.baseApi + file.filePath,
              id: file.id
            }
          })
        }
      })
    },
    async fileDelete(file) { //删除附件
      if(!this.deliver.id) return
      let params = {
        fileId: file.id
      }
      await this.$ajax.get('/tool/delFilesByRef', {params}).then(resp => {
        if (resp.success) {
          return true
        }
        return false
      })
    },
    onOversize() {
      this.$notify.warning('文件大小不能超过1MB')
    },
  },
  components: {
    DeliverItem,
    FlowButtons,
    ImagePreview
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .popup {
    width: 80%;
    height: 100%;
  }
  .my-swipe {
    margin-top: 50px;
    color: black;
    font-size: 20px;
    text-align: center;
    background-color: black;
  }
  .imgs {
    margin-top: 4px;
    width: 20rem;
    height: 10rem
  }
</style>
